;;;
;;; This file is part of scheme-x-interface.
;;;
;;; scheme-x-interface is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 2 of the License, or
;;; (at your option) any later version.
;;;
;;; scheme-x-interface is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with scheme-x-interface.  If not, see <http://www.gnu.org/licenses/>.
;;;



(library
 (sxi impl-dep plt socket)
 (export open-file-stream-socket)
 (import (rnrs base (6))
	 (rnrs io ports (6))
	 ;;plt foreign function interface
	 (scheme foreign))
 
 (unsafe!)

 ;;raw stuff


 (define libc (ffi-lib "libc" "6"))
 (define socket-helper (ffi-lib "libsocket_helper" "0.0.1"))

 (define c:read-socket (get-ffi-obj 'read_socket 
				    socket-helper 
				    (_fun _int _bytes _int _int -> _int)))
 (define c:write-socket (get-ffi-obj 'write_socket 
				     socket-helper 
				     (_fun _int _bytes _int _int -> _int)))
 (define c:close (get-ffi-obj 'close libc (_fun _int -> _int)))
 (define c:get-unix-socket (get-ffi-obj 'get_unix_socket 
					socket-helper 
					(_fun _int _int _string/utf-8 -> _int)))
 (define c:socket-stream (get-ffi-obj 'SCHEME_SOCK_STREAM 
				      socket-helper 
				      _int))
 (define c:socket-dgram (get-ffi-obj 'SCHEME_SOCK_DGRAM 
				      socket-helper 
				      _int))


 (define open-file-stream-socket
   (lambda (path abstract)
     (let ([socket-id (c:get-unix-socket c:socket-stream abstract path)])
       (make-custom-binary-input/output-port 
	path
	(lambda (bytevector start count)
	  (c:read-socket socket-id bytevector start count))
	(lambda (bytevector start count)
	  (c:write-socket socket-id bytevector start count))
	#f
	#f
	(lambda ()
	  (c:close socket-id))))))

)

